<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 新增开屏页
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>

      <Form
        ref="formValidate2"
        :model="bloc.model"
        :rules="ruleValidate3"
        :label-width="111"
        style="padding:50px 100px 0 100px;width: 860px"
      >

        <FormItem label="品牌商:" prop="companyId" required v-if="tepee === '1'">
          <CompanySeletorSingle :companyId="bloc.model.companyId" WishesDetailBloc
                                @on-change="value => companyChange(value)" v-if="tepee === '1'"></CompanySeletorSingle>
        </FormItem>
        <FormItem label="经销商:" prop="agentId" v-if="tepee === '1'">
          <i-select v-model="bloc.model.agentId" filterable WishesDetailBloc clearable v-if="tepee === '1'" :disabled="this.bloc.model.agentId !== 1">
            <i-option v-for="item in bloc.sortList" :value="item.id" :key="item.id">{{ item.agentName }}</i-option>
          </i-select>
        </FormItem>

        <FormItem label="名称:" prop="wishName" required>
          <Input v-model="bloc.model.wishName" placeholder="最多15个字" WishesDetailBloc :maxlength="15"/>
        </FormItem>
        <FormItem label="倒计时(秒):" required>
          <Input v-model="bloc.model.screenOpeningTime" :precision="0" :max="120" :min="5" prop="screenOpeningTime" type="number" placeholder="倒计时时间"/>
        </FormItem>
        <FormItem label="展示时间:" required>
            <Row>
                <Col span="11">
                  <FormItem prop="startTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="开始时间" v-model="bloc.model.startTime"></DatePicker>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">-</Col>
                <Col span="11">
                  <FormItem prop="endTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="结束时间" v-model="bloc.model.endTime"></DatePicker>
                  </FormItem>
                </Col>
            </Row>
        </FormItem>

        <FormItem label="图片:" prop="imageurl" v-if="bloc.model.type === 'IMAGE'" required>
          <div class="video">
          <div class="demo-upload-list" v-for="(item, index) in fileList" :key="index">
            <template v-if="item.status1 === 'finished'">
              <img v-if="isimage" :src="item.imageurl">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(item.imageurl)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            ref="upload"
            :show-upload-list="false"
            :action="imageAndVideoPath"
            :max-size="maxSize"
            :format="['jpg','png','gif','mp4']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError1"
            :on-exceeded-size="handleMaxSize1"
            :on-success="handleSuccess"
            :before-upload="beforeupload"
            style="display: inline-block;width:58px;margin-left:15px"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="visible">
              <img :src="imgUrl" v-if="visible" style="width: 100%">
            </Modal>
          </Upload>
          </div>
          <div style="margin-top: 10px"><p>支持 JPG、PNG、GIF、MP4格式，图片小于2M，视频小于6M，尺寸参考 720*1600</p></div>
        </FormItem>
        <FormItem label="视频:" prop="imageurl" v-if="bloc.model.type === 'VIDEO'" required>
          <div v-for="(item, index) in fileList" :key="item.imageurl">
            <template v-if="item.status1 === 'finished'">
              <video height="300" width="400" controls :src="item.imageurl"></video>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <div class="video">
            <Upload
              ref="upload"
              :show-upload-list="false"
              :action="imageAndVideoPath"
              :max-size="maxSize"
              :format="['jpg','png','gif','mp4']"
              :headers="uploadHeaders"
              :on-format-error="handleFormatError1"
              :on-exceeded-size="handleMaxSize1"
              :on-progress="handleProgress"
              :on-success="handleSuccess"
              :before-upload="beforeupload"
              :on-error="handleError"
              style="display: inline-block;width:58px;margin-left:15px"
            >
              <div style="width: 58px;height:58px;line-height: 58px;" :disabled="elProgress">
                <Icon type="ios-camera" size="20"></Icon>
              </div>
              <Modal title="View Image" v-model="visible">
                <img :src="imgUrl" style="width: 100%">
              </Modal>
            </Upload>
            <p style="margin-left: 15px" v-if="!elProgress">支持 JPG、PNG、GIF、MP4格式，图片小于2M，视频小于6M</p>
            <p style="margin-left: 15px" v-if="elProgress">正在上传请等待...</p>
          </div>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px;">
        <Button style="width: 100px;height: 40px;" @click="handleCancel()">返回</Button>
        <AppButton
          ref="save"
          style="margin-left: 30px;width: 100px;height: 40px;"
          type="primary"
          :disabled="bloc.isDetail"
          @click="addModel('formValidate2')"
        >确认
        </AppButton>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">
    import {Component, Vue} from 'vue-property-decorator';
    import {store} from '@/store/Store';
    import {baseUrl} from '@/base/Request';
    import {Route} from 'vue-router';
    import {FormBloc} from './AddBloc';
    import {isEmpty} from '@/base/util/Strings';
    import CompanySeletorSingle from '@/component/CompanySeletorSingle.vue';
    import {AppButton} from '@/type/AppButton';
import { FormItem } from 'view-design';

    @Component({
        components: {CompanySeletorSingle}
    })

    export default class extends Vue {
        disabled: boolean = true;
        beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
            next(vm => {
                vm.bloc.type = vm.tepee;
                if (vm.isHasMemberInfo) {
                    vm.bloc.getCompanyList(vm.bloc.company.pageIndex, vm.bloc.company.pageSize, 'ASC');
                } else {
                    this.$Message.error('加载失败');
                }
            });
        }
        bloc = new FormBloc();
        validateId = (rule: any, value: string, callback: any) => {
            isEmpty(this.bloc.model.companyId) || this.bloc.model.companyId === 0
                ? callback(new Error('所属品牌商不能为空')) : callback();
        };
        get tepee() {
            return store.state.user.tepee
        }
        get uploadHeaders() {
            return {
                'Authorization': 'Bearer ' + store.state.auth.accessToken
            }
        };
        imgUrl = '';
        visible = false;
        get fileList() {
            return this.bloc.fileList.map(x => {
                return {'name': 'name', 'imageurl': x, 'status1': 'finished'};
            });
        }
        get isHasMemberInfo() {
            const sessinStr = sessionStorage.getItem('MEMBER_INFO');
            const info = sessinStr ? JSON.parse(sessinStr) : undefined;
            if (info) {
                this.bloc.model.companyId = info[0].companyId;
                this.bloc.getAllSort(1, 100, 'ASC');
                this.bloc.model.agentId = info[0].agentId;
                this.bloc.model.targetAccounts = info.map((x) => x.id);
                this.bloc.model.targetGroup = 'PART_MEMBER';
                this.bloc.isinfo = true;
            }
            return !isEmpty(info);
        }
        handleView(url) {
            this.imgUrl = url;
            this.visible = true;
        }
        handleRemove(file) {
            this.bloc.fileList.splice(this.bloc.fileList.indexOf(file), 1);
        }
        ruleValidate3: any = {
            companyId: [
                {validator: this.validateId, trigger: 'blur'}
            ],
            // agentId: [
            //     {validator: this.validateId, trigger: 'blur'}
            // ],
            imageurl: [
                {required: true, message: '图片/视频不能为空', trigger: 'change'}
            ],
            wishName: [{required: true, message: '名称不能为空', trigger: 'blur'}],
            screenOpeningTime: [{required: true, type:'number', message: '倒计时不能为空', trigger: 'blur'}],
            startTime: [{required: true, type:'date', message: '请选择开始时间', trigger: 'change'}],
            endTime: [{required: true, type:'date', message: '请选择结束时间', trigger: 'change'}],
        };
        $refs!: {
            save: AppButton
            formValidate2: HTMLFormElement
        };
        enable = false;
        switchStatus(status) {
            if (status) {
                this.bloc.model.isAble = 1
            } else {
                this.bloc.model.isAble = 0
            }
        };
        companyChange(companyId) {
            this.bloc.model.companyId = companyId;
            this.bloc
                .getAllSort(this.bloc.angent.pageIndex, 1000, 'DESC')
                .then((res) => {})
                .finally(() => {});
        }
        // 添加
        addModel(name) {
          this.$refs[name].validate(valid => {
            if (valid) {
              this.$refs.save.bloc.loading = true;
              if (isNaN(this.bloc.model.agentId)) {
                  this.bloc.model.agentId = 1;
              }
              if (this.tepee !== '1') {
                  this.bloc.model.agentId = store.state.user.agent.id;
                  this.bloc.model.companyId = store.state.user.agent.companyId;
              }
              if(this.bloc.model.screenOpeningTime<=0){
                this.$Message.error('请输入倒计时');
                return
              }
              if(this.bloc.model.startTime){
                this.bloc.model.startTime=this.bloc.model.startTime.getTime()
              }
              if(this.bloc.model.endTime){
                this.bloc.model.endTime=this.bloc.model.endTime.getTime()
              }
              this.bloc.addModel(this.bloc.model).then(res => {
                  this.$Message.success('确认成功');
                  this.$refs.save.bloc.loading = false;
                  this.handleOK();
              }).catch(err => {
                  // this.$Message.error('保存失败');
                  this.$Message.error(err.message);
                  this.$refs.save.bloc.loading = false;
              });
            }
          });
        }
        imageAndVideoPath = '';
        maxSize = 2048;
        elProgress=false;
        isvideo : boolean | undefined;
        isimage : boolean | undefined;
        handleProgress() {
            this.elProgress = true;
        }
        handleError() {
            this.elProgress = false;
            this.$Message.error('上传失败');
        }
        beforeupload(file) {
             this.isvideo = file.type === 'video/mp4';
             this.isimage = new RegExp('^image').test(file.type);
            if (this.isimage) {
                this.bloc.model.type = 'IMAGE';
                return new Promise<void>((resolve) => {
                    this.$nextTick(() => {
                        this.imageAndVideoPath = `${baseUrl}/api/upload/image`;
                        this.maxSize = 2048;
                        resolve();
                    })
                })
            } else if (this.isvideo) { // 判断是否满足音频格式，如果满足，动态重写，上传音频时的路径
                this.bloc.model.type = 'VIDEO';
                return new Promise<void>((resolve) => {
                    this.$nextTick(() => {
                        this.imageAndVideoPath = `${baseUrl}/api/upload/video`;
                        this.maxSize = 6144;
                        resolve();
                    })
                })
            } else { // 如果上传文件不满足规定格式，则返回 false ，并提示，终止上传，不用配置上传路径。
                this.$Message.error('请选择格式为JPG、PNG、GIF、MP4格式的文件');
                return false;
            }
        }
        handleFormatError1(file) {
            this.$Message.error('请选择格式为JPG、PNG、GIF、MP4格式的文件')
        }
        handleMaxSize1(file) {
            if (this.isvideo) {
                this.$Message.error('视频大小不能超过6M');
            } else {
                this.$Message.error('图片大小不能超过2M');
            }
        }
        handleSuccess(res, file) {
            this.elProgress = false;
            if (this.isimage) {
                this.bloc.model.imageurl = res.data[0];
            } else {
                this.bloc.model.imageurl = res.data;
            }
            if (this.bloc.fileList.length > 0) {
                this.bloc.fileList = []
            }
            this.bloc.fileList.push(this.bloc.model.imageurl)
        }
        handleCancel() {
            if (this.bloc.isinfo) {
                this.$router.push({path: `/member`});
            } else {
                this.$router.push({path: `/banners/nav/wishes`});
            }
        }
        handleOK() {
            this.$router.push({path: `/banners/nav/wishes`});
        }
    }
</script>

<style lang="less" scoped>
  /deep/ .ivu-form-item-content {
    justify-content: start !important;
    align-items: center !important;
  }
  /deep/ .ivu-form-item-label {
    padding-top: 0;
  }
  .video {
    display: flex;
  }
</style>
